﻿''' <summary>
''' 车载启停记录查询
''' 何湘红 20091113 修改
''' </summary>
''' <remarks></remarks>
Public Class HDStartStopCarForm

    Dim pi As ProjectInfo.CarProjectInfo = Nothing




    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub HDStartStopCarForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'init(ProjectListForm.pi)
        LoadProjectList()
        'Me.cmsHDSelect.Visible = False
        'Me.lblProjectName.Text = pi.ProjectName + " >>> 启停记录查询："
    End Sub
    Private Sub init(ByVal prj As ProjectInfo.CarProjectInfo)
        pi = prj
        'Me.lblProjectName.Text = pi.ProjectName + " >>> 启停记录查询："
    End Sub

    Public Sub FormatDataGridViewData()

        'me.dgvStartUpDataSelect.
        For i As Integer = 0 To dgvStartUpDataSelect.RowCount - 1
            For j As Integer = 0 To dgvStartUpDataSelect.ColumnCount - 1
                Dim UpdateStatus As String = dgvStartUpDataSelect.Rows(i).Cells("UpdateStatus").Value

                If UpdateStatus.Equals("0") Then
                    dgvStartUpDataSelect.Rows(i).Cells("UpdateStatus").Value = "未上传"
                ElseIf UpdateStatus.Equals("1") Then
                    dgvStartUpDataSelect.Rows(i).Cells("UpdateStatus").Value = "未完成"
                ElseIf UpdateStatus.Equals("2") Then
                    dgvStartUpDataSelect.Rows(i).Cells("UpdateStatus").Value = "已完成"
                ElseIf UpdateStatus.Equals("3") Then
                    dgvStartUpDataSelect.Rows(i).Cells("UpdateStatus").Value = "尚未完成"

                End If

            Next
        Next
    End Sub
    ''' <summary>
    ''' 获取数据
    ''' </summary>
    ''' <param name="projectId"></param>
    ''' <param name="startTime"></param>
    ''' <param name="endTime"></param>
    ''' <remarks></remarks>
    Public Sub GetStartUpCarData(ByVal projectId As String, ByVal startTime As DateTime, ByVal endTime As DateTime)
        dgvStartUpDataSelect.DataSource = CarHDStartUpService.GetHDStartUpCarList(projectId, startTime, endTime)
        FormatDataGridViewData() '格式DataGridView数据
        GetDataGridViewISNull()
    End Sub

    Public Sub GetDataGridViewISNull()
        Dim count As Integer = Me.dgvStartUpDataSelect.Rows.Count

        If count <= 0 Then
            msg.Show("你查询的范围内没有数据,请重置！")
        End If

    End Sub

    '点击查询
    Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
        ' GetStartUpCarData()
        Dim startTime As DateTime
        startTime = AdjustDateTime(Me.dtpFrom.Value)

        Dim endTime As DateTime
        endTime = AdjustDateTime(Me.dtpTo.Value)


        If Me.cboCar.SelectedItem IsNot Nothing Then
            GetStartUpCarData(pi.ProId, startTime, endTime)
            Me.btnPrint.Enabled = True
        Else
            msg.Show("还没有选中工程！")
        End If



    End Sub

    ''' <summary>
    ''' 格式化时间
    ''' </summary>
    ''' <param name="dt"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function AdjustDateTime(ByVal dt As DateTime) As DateTime

        Dim s As Integer
        s = (dt.Hour * 3600 + dt.Minute * 60 + dt.Second) Mod HIST_SAVE_INTERVAL_TIME
        Return dt.AddSeconds(+(10 - s))

    End Function

    Private Shared index As Integer

    ''' <summary>
    ''' 点击跳转到历史数据界面
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub dgvStartUpDataSelect_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvStartUpDataSelect.CellDoubleClick

        'index = e.RowIndex
        Dim id As String = dgvStartUpDataSelect.Rows(e.RowIndex).Cells("Id").Value
        Dim projectId As String = pi.ProId
        Dim projectName As String = pi.CarProjectName
        Dim startTime As String = AdjustDateTime(dgvStartUpDataSelect.Rows(e.RowIndex).Cells("BeginTime").Value)
        Dim endTime As String
        If dgvStartUpDataSelect.Rows(index).Cells("endTime").Value > Date.Now Then
            endTime = Date.Now.ToString
        Else
            endTime = dgvStartUpDataSelect.Rows(index).Cells("endTime").Value
        End If
        Dim beginAddress As String = dgvStartUpDataSelect.Rows(e.RowIndex).Cells("BeginAddress").Value
        Dim endAddress As String = dgvStartUpDataSelect.Rows(e.RowIndex).Cells("EndAddress").Value
        Dim carrier As String = dgvStartUpDataSelect.Rows(e.RowIndex).Cells("Carrier").Value
        'msg.Show("点击" + e.ColumnIndex().ToString + "列 " + e.RowIndex.ToString + "行 " + id + " ID号")
        Dim frm As New HDTimeCarForm(projectId, id, projectName, startTime, endTime, beginAddress, endAddress, carrier)
        frm.ShowDialog()



        'End If
    End Sub

    Private Sub dgvStartUpDataSelect_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgvStartUpDataSelect.RowPostPaint
        Dim brush As System.Drawing.Brush = New SolidBrush(dgvStartUpDataSelect.RowHeadersDefaultCellStyle.ForeColor)

        e.Graphics.DrawString((e.RowIndex + 1).ToString(), dgvStartUpDataSelect.DefaultCellStyle.Font, brush, e.RowBounds.Location.X + 12, e.RowBounds.Y + 5)
    End Sub

    Private Sub LoadProjectList()
        Dim prjList As IList(Of ProjectInfo.CarProjectInfo) = CarProjectService.GetAllCarProjectInfo
        Dim count = prjList.Count
        If count > 0 Then
            Me.cboCar.DataSource = prjList
            Me.cboCar.DisplayMember = "CarProjectName"
            Me.cboCar.ValueMember = "ProId"
        End If
    End Sub

    Private Sub cboCar_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCar.SelectedValueChanged

        If Me.cboCar.SelectedValue.GetType().Name.Equals("CarProjectInfo") Then
            'Dim projectId As String = Me.cboCar.SelectedValue
            'Dim projectItem As ProjectInfo.CarProjectInfo = CarProjectService.GetProjectById(projectId)
            'init(projectItem)
        Else
            System.Diagnostics.Debug.WriteLine(Me.cboCar.SelectedValue)
            Dim projectId As String = Me.cboCar.SelectedValue
            'pId = Me.cboCar.SelectedValue
            Dim projectItem As ProjectInfo.CarProjectInfo = CarProjectService.GetProjectById(projectId)
            init(projectItem)
        End If


        'System.Diagnostics.Debug.WriteLine(Me.cboCar.SelectedValue)
    End Sub
    Dim cols(100) As String '定义保存列对应的属性名
    Dim headers(100) As String '用于保存头
    Dim tArray As New ArrayList()
    Dim hArray As New ArrayList()

    '点击打印按钮时
    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        Print()
        sender.Enabled = True
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub Print()
        Dim dt As IList(Of ProjectInfo.CarHDStartUpItem)
        dt = CType(Me.dgvStartUpDataSelect.DataSource, IList(Of ProjectInfo.CarHDStartUpItem))
        If dt Is Nothing OrElse dt.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        Dim objExcel As New Excel.Application

        Dim wb As Excel.Workbook = objExcel.Workbooks.Add()

        ReDim Preserve cols(100)


        Dim index As Integer = 0
        cols(index) = "序号"
        headers(index) = "序号"
        For i As Integer = 0 To Me.dgvStartUpDataSelect.Columns.Count - 1
            If Me.dgvStartUpDataSelect.Columns(i).Visible Then
                index += 1
                cols(index) = Me.dgvStartUpDataSelect.Columns(i).DataPropertyName '添加列名
                headers(index) = Me.dgvStartUpDataSelect.Columns(i).HeaderText '添加列头文本
            End If
        Next

        ReDim Preserve cols(index)

      
        Dim values(dt.Count, cols.Length + 1) As Object 'cols.Length + 1:时间为2列


        '添加报表的头
        For j As Integer = 0 To cols.Length - 1
            If j > 1 Then
                values(0, j + 1) = headers(j) 'j+1:跳过时间2列(共2列)
            Else
                values(0, j) = headers(j)
            End If
        Next

        '添加报表的身子
        For i As Integer = 0 To dt.Count - 1
            Dim r As ProjectInfo.CarHDStartUpItem = dt.Item(i)
            values(i + 1, 0) = i + 1
            For j As Integer = 1 To cols.Length - 1 '跳过GridView第一列
                If j > 1 Then
                    values(i + 1, j + 1) = dgvStartUpDataSelect.Rows(i).Cells(cols(j).ToString).Value ' r(cols(j)) 'j+1:跳过时间2列(共2列)
                Else
                    values(i + 1, j) = dgvStartUpDataSelect.Rows(i).Cells(cols(j).ToString).Value 'r(cols(j))
                End If
            Next
        Next

       

        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
           

            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.Font.Size = 10
            objExcel.Selection.ColumnWidth = 10


            '序号
            objExcel.Range("A1", "A" & (dt.Count + 1)).ColumnWidth = 5


           
            objExcel.Range("B1", objExcel.Cells(dt.Count + 1, 3)).ColumnWidth = 10
            objExcel.Range("B1", objExcel.Cells(dt.Count + 1, 3)).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

            'objExcel.Range("C1", objExcel.Cells(dt.Count + 1, 3)).Insert(Excel.XlInsertShiftDirection.xlShiftToRight) '插入合并列
            objExcel.Range("C1", objExcel.Cells(dt.Count + 1, 4)).ColumnWidth = 10
            objExcel.Range("C1", objExcel.Cells(dt.Count + 1, 4)).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"


            ' Dim totalIndex As Integer = 4 + tArray.Count + hArray.Count
            '设置温湿度列宽; 2008.10.31
            'objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Count + 1, totalIndex)).ColumnWidth = 6
            'objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Count + 1, totalIndex)).NumberFormatLocal = "0.00"

            '设置温湿度统计列宽; 2008.10.31
            'objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Count + 1, 26)).ColumnWidth = 8
            'objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Count + 1, 26)).NumberFormatLocal = "0.00"
            'objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Count + 1, totalIndex - 1 + IIf(tArray.Count > 0, 3, 0) + IIf(hArray.Count > 0, 3, 0))).Interior.Color = RGB(255, 221, 221) 'array.count > 0

            'Dim pageRow As Integer = 27 '不包括统计的3行; 2008.10.31
            Dim statRow As Integer = 3
            Dim totalCount As Integer = Math.Ceiling(dt.Count / 30) * 30 - statRow
            If totalCount < dt.Count Then
                totalCount += statRow
            End If
            '合并单元格
            Dim range As Excel.Range
            range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3)) '合并日期单元格(dt.Rows.Count); 2008.10.31
            range.Merge(True)
            'For i As Integer = 1 To totalCount + 1
            '    range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3))
            '    range.Merge(True)
            'Next
            '合并统计单元格
            ' range = objExcel.Range(objExcel.Cells(totalCount + 2, 1), objExcel.Cells(totalCount + 4, 2)) '2008.10.31
            'range = objExcel.Range(objExcel.Cells(bRow - 2, 1), objExcel.Cells(bRow, 2))
            'range.Merge()
            'range.Value2 = "统计"
            'range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            'range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
            'range.Font.Size = 20

            'cols.Length + 1:时间为2列
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Count + 1, cols.Length + 1)).Value2 = values

            '添加统计信息
            'Dim statRange As Excel.Range
            'statRange = objExcel.Range(objExcel.Cells(totalCount + 2, 3), objExcel.Cells(totalCount + 4, cols.Length + 1)) '2008.10.31
            'statRange = objExcel.Range(objExcel.Cells(bRow - 2, 3), objExcel.Cells(bRow, cols.Length + 1))
            'statRange.Value2 = statValues
            'statRange.Interior.Color = RGB(221, 221, 221)
            'statRange.Interior.Pattern = 4
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Color = RGB(221, 221, 221)
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Pattern = 4

            '设置边框
            range = objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(totalCount + 1, cols.Length + 1)) '设置统计边框，把totalCount+4改成totalCount+1
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous

            objExcel.Columns.AutoFit()
            '设置保护
            Try
                objExcel.ActiveSheet.Protect(pwd, _
                            AllowFormattingCells:=False, _
                            AllowFormattingColumns:=False, _
                            AllowFormattingRows:=False, _
                            AllowInsertingColumns:=False, _
                            AllowInsertingRows:=False, _
                            AllowInsertingHyperlinks:=False, _
                            AllowDeletingColumns:=False, _
                            AllowDeletingRows:=False _
                )
            Catch ex As Exception
                objExcel.ActiveSheet.Protect(pwd)
            End Try

            '温湿度值
            Dim ws As Excel.Worksheet = objExcel.ActiveSheet
            With ws.PageSetup
                .LeftHeader = "&G" & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .CenterHeader = String.Format("&""宋体,加粗""&28 {0}车载启停记录查询 ", Me.cboCar.SelectedValue.ToString)
                .RightHeader = vbCr & vbCr & vbCr & "共&N页 第&P页"
                .LeftFooter = "养护员："
                .CenterFooter = ""
                .RightFooter = "打印日期：&D &T"
                .LeftMargin = objExcel.Application.InchesToPoints(0.6)
                .RightMargin = objExcel.Application.InchesToPoints(0.4)
                .TopMargin = objExcel.Application.InchesToPoints(1.08)
                .BottomMargin = objExcel.Application.InchesToPoints(0.68)
                .HeaderMargin = objExcel.Application.InchesToPoints(0.22)
                .FooterMargin = objExcel.Application.InchesToPoints(0.5)
                .PrintHeadings = False
                .PrintGridlines = True
                '.PrintComments = objExcel.xlPrintNoComments
                ''.PrintQuality = 300
                .CenterHorizontally = False
                .CenterVertically = False
                '.Orientation = objExcel.xlPortrait
                .Draft = False
                '.PaperSize = Excel.XlPaperSize.xlPaperA4
                .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印
                '.FirstPageNumber = objExcel.xlAutomatic
                '.Order = objExcel.xlDownThenOver
                '.BlackAndWhite = False
                .Zoom = 100
                '.PrintErrors = objExcel.xlPrintErrorsDisplayed

                '.PrintArea = "A1:U" & bRow
                .FitToPagesWide = 1
                .FitToPagesTall = 1
                .PrintTitleRows = "$1:$1"

                Try

                    With .LeftHeaderPicture
                        .Filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\ClientLogo.jpg"
                        .Height = 68
                        .Width = 68
                        .LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoFalse
                        .LockAspectRatio = 0
                    End With

                Catch ex As Exception
                    .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                    Debug.WriteLine("页眉图片" & ex.ToString())
                End Try

            End With
            'excel.printpreview()
            'excel.PrintPreview()

            objExcel.Visible = True
            'objExcel.ActiveWindow.View = Excel.XlWindowView.xlPageBreakPreview
            objExcel.ActiveWindow.SelectedSheets.PrintPreview()
            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally
            Try
                If objExcel.ActiveWindow.View = Excel.XlWindowView.xlNormalView Then '分页预览
                    'objExcel.ActiveSheet.Unprotect(pwd)
                    wb.Close(False, False)
                    objExcel.Workbooks.Close()
                    objExcel.DisplayAlerts = False
                    objExcel.Quit()
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
                    wb = Nothing
                    objExcel = Nothing
                    GC.Collect()
                End If
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try


        End Try
    End Sub

    Private Sub dgvStartUpDataSelect_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles dgvStartUpDataSelect.DataBindingComplete
        Me.dgvStartUpDataSelect.Columns("BeginTime").DisplayIndex = 0
        Me.dgvStartUpDataSelect.Columns("BeginTime").Width = 150
        Me.dgvStartUpDataSelect.Columns("EndTime").DisplayIndex = 1
        Me.dgvStartUpDataSelect.Columns("EndTime").Width = 150
        Me.dgvStartUpDataSelect.Columns("BeginAddress").DisplayIndex = 2
        Me.dgvStartUpDataSelect.Columns("endAddress").DisplayIndex = 3
        Me.dgvStartUpDataSelect.Columns("Shipper").DisplayIndex = 4
        Me.dgvStartUpDataSelect.Columns("Carrier").DisplayIndex = 5
        Me.dgvStartUpDataSelect.Columns("Receiver").DisplayIndex = 6
        Me.dgvStartUpDataSelect.Columns("UpdateStatus").DisplayIndex = 7
    End Sub

    Private Sub tsmHDSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmHDSelect.Click

        Dim id As String = dgvStartUpDataSelect.Rows(index).Cells("Id").Value
        Dim projectId As String = pi.ProId
        'Dim projectId As String = pId
        Dim projectName As String = pi.CarProjectName
        Dim startTime As String = AdjustDateTime(dgvStartUpDataSelect.Rows(index).Cells("BeginTime").Value)
        Dim endTime As String

        If dgvStartUpDataSelect.Rows(index).Cells("endTime").Value > Date.Now Then
            endTime = Date.Now.ToString
        Else
            endTime = dgvStartUpDataSelect.Rows(index).Cells("endTime").Value
        End If
        Dim beginAddress As String = dgvStartUpDataSelect.Rows(index).Cells("BeginAddress").Value
        Dim endAddress As String = dgvStartUpDataSelect.Rows(index).Cells("EndAddress").Value
        Dim carrier As String = dgvStartUpDataSelect.Rows(index).Cells("Carrier").Value
        'msg.Show("点击" + e.ColumnIndex().ToString + "列 " + e.RowIndex.ToString + "行 " + id + " ID号")
        Dim frm As New HDTimeCarForm(projectId, id, projectName, startTime, endTime, beginAddress, endAddress, carrier)
        frm.ShowDialog()
    End Sub


    Private Sub dgvStartUpDataSelect_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvStartUpDataSelect.SelectionChanged
        index = Me.dgvStartUpDataSelect.CurrentCell.RowIndex
        Me.cmsHDSelect.Enabled = True
        Me.tsmHDSelect.Enabled = True


    End Sub


   
End Class